package com.yueshop.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;


@Configuration
public class MyRabbitConfig {


    RabbitTemplate rabbitTemplate;


    @Primary
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate=rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageConverter());
        initRabbitTemplate();
        return rabbitTemplate;
    }


    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }


    //@PostConstruct // 配置类对象创建完成之后 执行这个方法
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *
             * @param correlationData 当前消息的唯一关联数据(消息的唯一id)
             * @param ack  消息是否成功收到 true 收到 false 没收到
             * @param cause 失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                //服务器收到消息
                System.out.println("correlationData==?"+correlationData+"ack==>"+ack+"cause==>"+cause);
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /** 只要消息 没有投递到指定的队列 这个回调才会触发
             * @param message  投递失败的消息详细信息
             * @param replyCode 回复的状态码
             * @param replyText  回复的文本内容
             * @param exchange   当时 要发送给哪个 交换机
             * @param routingKey  当时要使用哪一个路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                //出现错误了 修改数据库
                System.out.println("message=>"+message+" replyCode=>"+replyCode+" replyText=>"+replyText+" exchange=>"+exchange+" routingKey=>"+routingKey);
            }
        });

    }




}
